package cn.com.blueInfo.autoCode.database;

import cn.com.blueInfo.bpm.person.request.UserAccountDTO;
import cn.com.blueInfo.bpm.person.response.UserAccountVO;
import cn.com.blueInfo.bpm.person.service.UserAccountService;
import cn.com.blueInfo.bpm.system.enums.DynamicFormFieldHidden;
import cn.com.blueInfo.bpm.system.enums.DynamicFormFieldRequired;
import cn.com.blueInfo.bpm.system.enums.DynamicFormType;
import cn.com.blueInfo.bpm.system.request.ApplicationDTO;
import cn.com.blueInfo.bpm.system.request.DynamicFormDTO;
import cn.com.blueInfo.bpm.system.request.DynamicFormFieldDTO;
import cn.com.blueInfo.bpm.system.request.TenantDTO;
import cn.com.blueInfo.bpm.system.response.ApplicationVO;
import cn.com.blueInfo.bpm.system.response.DynamicFormVO;
import cn.com.blueInfo.bpm.system.response.TenantVO;
import cn.com.blueInfo.bpm.system.service.ApplicationService;
import cn.com.blueInfo.bpm.system.service.DynamicFormFieldService;
import cn.com.blueInfo.bpm.system.service.DynamicFormService;
import cn.com.blueInfo.bpm.system.service.TenantService;
import cn.com.blueInfo.core.entity.CurrentLoginUserInfo;
import cn.com.blueInfo.utils.result.ResultInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class CreateDynamicFormData {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DynamicFormService dynamicFormService;

    @Autowired
    private DynamicFormFieldService dynamicFormFieldService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private CurrentLoginUserInfo currentLoginUserInfo;

    private static final String[] FIELDS = {"application_id", "create_time", "create_user_id", "deleted", "delete_time",
            "delete_user_id", "extend1", "extend2", "extend3", "id", "order_number", "remark", "status", "tenant_id",
            "update_time", "update_user_id"};

    public void handler() {
        loginInfo();
        List<DynamicFormDTO> dynamicFormList = addFormData();
        addFormFieldData(dynamicFormList);
    }

    private List<DynamicFormDTO> addFormData() {
        String querySql = "select table_name, table_comment from information_schema.`TABLES` where table_schema = 'haiyuan_dev'";
        List<Map<String, Object>> resultDataList = jdbcTemplate.queryForList(querySql);
        List<DynamicFormDTO> dynamicFormList = new ArrayList<>();
        for (Map<String, Object> oneData : resultDataList) {
            DynamicFormDTO dynamicForm = new DynamicFormDTO();
            dynamicForm.setFormCode((String) oneData.get("table_name"));
            dynamicForm.setFormName((String) oneData.get("table_comment"));
            dynamicForm.setFormType(DynamicFormType.SYSTEM_BUILT_IN);
            dynamicFormList.add(dynamicForm);
        }
        for (DynamicFormDTO dynamicForm : dynamicFormList) dynamicFormService.addDynamicForm(dynamicForm);
        return dynamicFormList;
    }

    private void addFormFieldData(List<DynamicFormDTO> dynamicFormList) {
        for (DynamicFormDTO dynamicForm : dynamicFormList) {
            DynamicFormDTO.QueryDTO dynamicFormQueryDTO = new DynamicFormDTO.QueryDTO();
            dynamicFormQueryDTO.setFormCode(dynamicForm.getFormCode());
            ResultInfo<Page<DynamicFormVO>> dynamicFormPage =
                    dynamicFormService.queryDynamicFormPage(dynamicFormQueryDTO);
            DynamicFormVO dynamicFormVO = dynamicFormPage.getData().getRecords().get(0);

            String tableName = dynamicFormVO.getFormCode();

            setDynamicFormFieldInfo(tableName, Long.parseLong(dynamicFormVO.getId()));

        }
    }

    private void setDynamicFormFieldInfo(String tableName, Long dynamicFormId) {
        List<DynamicFormFieldDTO> dynamicFormFieldList = new ArrayList<>();
        String querySql = "select " +
                "column_name, column_comment, data_type, is_nullable, column_default, column_type " +
                "from information_schema.`COLUMNS` " +
                "where table_schema = 'haiyuan_dev' and table_name = '" + tableName + "'";
        List<Map<String, Object>> resultDataList = jdbcTemplate.queryForList(querySql);
        for (Map<String, Object> oneData : resultDataList) {
            DynamicFormFieldDTO dynamicFormField = new DynamicFormFieldDTO();
            dynamicFormField.setFormId(dynamicFormId);
            String columnName = (String) oneData.get("column_name");
            dynamicFormField.setFieldName(columnName);

            String columnComment = (String) oneData.get("column_comment");
            columnComment = columnComment.contains("：") ? columnComment.substring(0, columnComment.indexOf("：")) :
                    columnComment.contains("（") ? columnComment.substring(0, columnComment.indexOf("（")) :
                            columnComment;
            dynamicFormField.setFieldLabel(columnComment);

            String dataType = (String) oneData.get("data_type");
            dynamicFormField.setFieldType(dataType);

            String isNullable = (String) oneData.get("is_nullable");
            if ("YES".equals(isNullable)) dynamicFormField.setRequired(DynamicFormFieldRequired.NOT_REQUIRED);
            else dynamicFormField.setRequired(DynamicFormFieldRequired.REQUIRED);

            String columnDefault = (String) oneData.get("column_default");
            if (StringUtils.isNotBlank(columnDefault)) dynamicFormField.setDefaultValue(columnDefault);
            else dynamicFormField.setDefaultValue("");

            String columnType = (String) oneData.get("column_type");
            columnType = columnType.contains("(") ?
                    columnType.substring(columnType.indexOf("(") + 1, columnType.indexOf(")")) : "";
            if (StringUtils.isNotBlank(columnType)) dynamicFormField.setMaxLength(Integer.valueOf(columnType));

            if (isWriteColumn(columnName)) dynamicFormField.setHidden(DynamicFormFieldHidden.DEFAULT_HIDDEN);
            else dynamicFormField.setHidden(DynamicFormFieldHidden.DEFAULT_VISIBLE);

            dynamicFormFieldList.add(dynamicFormField);
        }
        for (DynamicFormFieldDTO oneDynamicFormField : dynamicFormFieldList)
            dynamicFormFieldService.addDynamicFormField(oneDynamicFormField);
    }

    private boolean isWriteColumn(String columnName) {
        for (String field : FIELDS) {
            if (field.equals(columnName))
                return true;
        }
        return false;
    }

    private void loginInfo() {
        ResultInfo<Page<TenantVO>> tenantPage = tenantService.queryTenantPage(new TenantDTO.QueryDTO());
        TenantVO tenantVO = tenantPage.getData().getRecords().get(0);
        currentLoginUserInfo.setTenantId(Long.parseLong(tenantVO.getId()));

        ResultInfo<Page<ApplicationVO>> applicationPage =
                applicationService.queryApplicationPage(new ApplicationDTO.QueryDTO());
        ApplicationVO applicationVO = applicationPage.getData().getRecords().get(0);
        currentLoginUserInfo.setApplicationId(Long.parseLong(applicationVO.getId()));

        ResultInfo<Page<UserAccountVO>> userAccountPage =
                userAccountService.queryUserAccountPage(new UserAccountDTO.QueryDTO());
        UserAccountVO userAccountVO = userAccountPage.getData().getRecords().get(0);
        currentLoginUserInfo.setUserId(Long.parseLong(userAccountVO.getId()));
    }



}
